'use client'

import { useState } from 'react'
import { VmsCourseSection } from '@/types/Model'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Edit, Trash2, GripVertical } from 'lucide-react'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useRouter } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import SectionEditDialog from './SectionEditDialog'

interface SortableSectionCardProps {
  section: VmsCourseSection
  index: number
  courseId: string
  onDelete: (sectionId: string) => Promise<void>
  onUpdate: (sectionData: Partial<VmsCourseSection>) => Promise<void>
}

export default function SortableSectionCard({ 
  section, 
  index, 
  courseId,
  onDelete,
  onUpdate
}: SortableSectionCardProps) {
  const router = useRouter()
  const [editDialogOpen, setEditDialogOpen] = useState(false)
  const [publishLoading, setPublishLoading] = useState(false)
  
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id: section.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  }

  // 点击标题进入内容编辑页面
  const handleTitleClick = () => {
    router.push(`/courses/${courseId}/sections/${section.id}/edit`)
  }

  // 点击编辑图标弹出对话框
  const handleEditClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    setEditDialogOpen(true)
  }

  // 一键发布/取消发布
  const handlePublishToggle = async (published: boolean) => {
    setPublishLoading(true)
    try {
      await onUpdate({
        id: section.id,
        published: published
      })
      toast({
        title: published ? '发布成功' : '取消发布成功',
        description: `小节"${section.title}"已${published ? '发布' : '取消发布'}`,
      })
    } catch (error) {
      console.error('更新发布状态失败:', error)
      toast({
        title: '操作失败',
        description: '更新发布状态失败，请重试',
        variant: 'destructive'
      })
    } finally {
      setPublishLoading(false)
    }
  }

  return (
    <>
      <div ref={setNodeRef} style={style} {...attributes}>
        <Card className="mb-4 border-slate-200/50 shadow-sm bg-white/80 backdrop-blur-sm hover:shadow-md transition-shadow">
          <CardContent className="p-4">
            <div className="flex items-start gap-4">
              <div 
                {...listeners}
                className="cursor-grab active:cursor-grabbing p-1 hover:bg-slate-100 rounded"
              >
                <GripVertical className="h-5 w-5 text-slate-400" />
              </div>
              
              <div className="flex-1">
                <div className="flex justify-between items-start mb-3">
                  {/* 点击标题进入内容编辑 */}
                  <div className="flex-1">
                    <h3 
                      className="text-lg font-semibold text-slate-900 cursor-pointer hover:text-blue-600 transition-colors mb-2"
                      onClick={handleTitleClick}
                      title="点击编辑内容"
                    >
                      {section.title}
                    </h3>
                    
                    {/* 发布状态显示和一键发布开关 */}
                    <div className="flex items-center gap-4">
                      <div className="flex items-center space-x-2">
                        <Switch
                          id={`publish-${section.id}`}
                          checked={section.published}
                          onCheckedChange={handlePublishToggle}
                          disabled={publishLoading}
                        />
                        <Label 
                          htmlFor={`publish-${section.id}`} 
                          className="text-sm font-medium text-slate-700 cursor-pointer"
                        >
                          {section.published ? '已发布' : '未发布'}
                        </Label>
                      </div>
                      
                      {section.published && (
                        <Badge className="bg-green-50 text-green-700 border-green-200">
                          已发布
                        </Badge>
                      )}
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    {/* 点击编辑图标弹出对话框 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={handleEditClick}
                      className="text-slate-600 hover:text-slate-900"
                      title="快速编辑"
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onDelete(section.id)}
                      className="text-rose-600 hover:text-rose-700"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
               
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
      
      {/* 编辑对话框 */}
      <SectionEditDialog
        section={section}
        open={editDialogOpen}
        onOpenChange={setEditDialogOpen}
        onSave={onUpdate}
      />
    </>
  )
}
